let app=getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    userInfo:{
      type:Object,
      value:null
    }
  },
  
  /**
   * 组件的初始数据
   */
  data: {
    giftList:[],
    goldNum:0,
    curIndex:null
  },

  lifetimes: {
    attached: function () {
      //console.log(app.globalData.userInfo);
      // 在组件实例进入页面节点树时执行
      wx.cloud.callFunction({
        name: 'getGiftList'
      }).then(res => {
        //console.log(res.result);
        let giftList = res.result.giftList;
        if (giftList && giftList.length > 0) {
          this.setData({
            giftList
          })
        }
      })

      wx.cloud.callFunction({
        name:'getGold'
      }).then(res=>{
        this.setData({
          goldNum: res.result.goldNum
        })
      })
    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
    },
  },

  pageLifetimes: {
    show: function () {
      // 页面被展示
      wx.cloud.callFunction({
        name: 'getGold'
      }).then(res => {
        this.setData({
          goldNum: res.result.goldNum
        })
      })
    },
    hide: function () {
      // 页面被隐藏
    },
    resize: function (size) {
      // 页面尺寸变化
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    _chooseGift(e){
      let i=e.currentTarget.dataset.index;
      this.setData({
        curIndex:i
      })
    },

    sendGift(e){
      //console.log(e);
      let curIndex=this.data.curIndex;
      let gift=this.data.giftList[curIndex];
      let fuserInfo=this.data.userInfo;
      //console.log(gift,fuserInfo);
      let gnum=this.data.goldNum;
      if(gnum<gift.price){
        wx.showModal({
          title: '提示',
          content: '金币不足,是否立即充值',
          showCancel: true,
          confirmText: '前往充值',
          confirmColor: 'blue',
          success: function(res) {
            if(res.confirm){
              wx.navigateTo({
                url: '../../pages/recharge/recharge',
              })
            }
          }
        });
        return;
      }
      wx.cloud.callFunction({
        name:'sendGift',
        data:{
          gift,
          fuserInfo,
          senderUserInfo: app.globalData.userInfo
        }
      }).then(res=>{
        if(res.result.code==0){
          this.setData({
            goldNum:this.data.goldNum-gift.price
          });
          wx.showToast({
            title: '成功赠送'+gift.name,
            icon:'none'
          });
        }
        else{
          wx.showToast({
            title: res.result.mes,
            icon:'none'
          })
        }
      })
    },
    showModel(){
      this.selectComponent('#popup1').showModal();
    }

  }
})
